package day19;

public class TestProducerAndConsumer {
	public static void main(String[] args) {
		MyStack ms = new MyStack();
		Thread producer1 = new ProducerThread(ms);
		Thread producer2 = new ProducerThread(ms);
		Thread consumer = new ConsumerThread(ms);
		producer1.start();
		producer2.start();
		consumer.start();
	}
}

class MyStack{
	private char[] cs = new char[6];
	private int index = 0;
	public synchronized void push(char c){
		while(index==6){
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		cs[index] = c;
		System.out.println(cs[index]+ " pushed!");
		index++;
		notifyAll();
	}
	public synchronized void pop(){
		while(index==0){
			try{
				wait();
			}catch(InterruptedException e){
				e.printStackTrace();
			}
		}
		index--;
		System.out.println(cs[index]+" poped!");
		notifyAll();
		cs[index] = '\0';
	}
	public void print(){
		for(int i=0; i<index; i++){
			System.out.print(cs[i]+"\t");
		}
		System.out.println();
	}
}

class ProducerThread extends Thread{
	private MyStack s;
	public ProducerThread(MyStack s){
		this.s = s;
	}
	public void run(){
		for(char c='A'; c<='Z'; c++){
			s.push(c);
			try{
				Thread.sleep(20);
			}catch(Exception e){
				e.printStackTrace();
			}
			s.print();
		}
	}
}

class ConsumerThread extends Thread{
	private MyStack s;
	public ConsumerThread(MyStack s){
		this.s = s;
	}
	public void run(){
		for(int i=0; i<26*2; i++){
			s.pop();
			try{
				Thread.sleep(40);
			}catch(Exception e){
				e.printStackTrace();
			}
			s.print();
		}
	}
}
